package com.xsoft.framework.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class CookieUtil {
	
	private static Logger logger = Logger.getLogger(CookieUtil.class);
	/**
	 * 从cookie中获取key对应的值
	 * @author mickey_shen
	 * @param key
	 * @param request
	 * @return
	 */
	public static String getCookieValue(String key,HttpServletRequest request)
	{
	     Cookie cookie[]=request.getCookies();
	     if(cookie==null)
	    	 return null;
	     for(int i=0;i<cookie.length;i++)
	     {
	    	 if(cookie[i].getName().equals(key))
	    	 {
	    		  return cookie[i].getValue();
	    	 }
	     }
		 return null;
    }
	
	public static void removeCookie(String name,HttpServletRequest request,HttpServletResponse response){
		Cookie cookies[]=request.getCookies();
	     if(cookies==null || cookies.length<1)
	     {
	    	 logger.error("请求里cookie为null");
	     }
	     for(int i=0;i<cookies.length;i++)
	     {
	    	 if(cookies[i].getName().equals(name))
	    	 {
	    		  Cookie cookie = cookies[i];
	    		  cookie.setMaxAge(0);//将当前COOKIE失效时间设置为0
	    		  response.addCookie(cookie);
	    	 }else{
	    		 logger.error("没有与key相匹配的cookie");
	    	 }
	     }
	}
	
	
	/**********************
	 * 
	 * @Description TODO (写入cookie信息)
	 * @author woyo.tandong
	 * @param key
	 * @param value
	 * @param domain
	 * @param maxAge
	 * @param path
	 * @param response
	 * @throws
	 */
	public static void writeCookie(String key,String value,String domain, Integer maxAge,String path,HttpServletResponse response){
		Cookie cookie=new Cookie(key,value);
		cookie.setDomain(domain);
		if (null != maxAge) {
		    cookie.setMaxAge(maxAge);
		}
		cookie.setPath(path);
		response.addCookie(cookie);
	}
	
}
